package com.example.mytips.projectCreateActions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.RefreshQueue;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class CreateExtensionAction extends AnAction {

    public static String classSuffix = "ACTION_";

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {

        Project project = e.getProject();
        assert project != null;

        // 获取项目根目录
        VirtualFile projectRoot = project.getBaseDir();

        // 获取当前选中的文件集合
        VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);

        if (files != null && files.length == 1) {
            VirtualFile file = files[0]; // 假设只处理第一个选中的文件

            // 集合中的第一个
            VirtualFile parent = file.getParent();
            if (parent == null) return;

            if (!file.isDirectory()) {
                String[] split = file.getName().split("\\.");
                // 文件名
                String fileName = classSuffix + split[0];
                String fileNameHasEnd = fileName + "." + file.getExtension();

                // 判断文件是否存在
                VirtualFile child = parent.findChild(fileNameHasEnd);

                if (child != null && child.exists()) {
                    Messages.showInfoMessage(project, fileNameHasEnd + "文件存在，不用重复创建", "提示");
                    return;
                }

                // 文件内容
                String content = getFileContent(projectRoot, file, classSuffix, split[0], split[0] + "State");

                ApplicationManager.getApplication().runWriteAction(new Runnable() {
                    @Override
                    public void run() {
                        // 这里放置需要执行的写操作
                        // 尝试写入
                        try {

                            ///根据parent得到一个子类的VirtualFile
                            VirtualFile newFile = parent.createChildData(this, fileNameHasEnd);

                            // 写入内容
                            newFile.setBinaryContent(content.getBytes(StandardCharsets.UTF_8));
                            // 刷新工程目录
                            RefreshQueue.getInstance().refresh(false, true, null, newFile.getParent());
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                });

            }
        }
    }


    public String getFileContent(VirtualFile projectRoot, VirtualFile file, String classSuffix, String fileName, String selectFileName) {
        List<String> list = new ArrayList();

        String lib = file.getPath().substring(projectRoot.getPath().length()).substring("/lib".length());
        String line = "import 'package:" + projectRoot.getName() + lib + "';";
        list.add(line);
        list.add("\n\n");

        list.add("extension " + classSuffix + fileName + " on " + selectFileName + " {\n");

        list.add("\tvoid onClick() {\n");
        list.add("\t\tprint(\"onClick\");\n");
        list.add("\t}\n");

        list.add("}");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            stringBuilder.append(list.get(i));
        }

        return stringBuilder.toString();
    }
}
